//
//  MineSettingVC.m
//  XJMCustomer
//  Created by Mr.hu on 2017/10/13.
//  Copyright © 2017年 Mr.hu. All rights reserved.

#import "MineSettingVC.h"
#import "MineSettingFirstCell.h"
#import "MineSettingSeconodCell.h"
#import "MineIntroSettingCell.h"
#import "NicknameAndPhoneCell.h"
#import "MineIntroUpdate.h"
#import "SettingExitBottom.h"
#import "MineSettingSkillCell.h"
#import "Customer_HelpCenter.h"
#import "MineAboutVC.h"
#import "AddSomepersonVC.h"
#import "SkillSelectViewController.h"
#import "AdviceFeedBackVC.h"
@interface MineSettingVC ()<UITableViewDelegate,UITableViewDataSource,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UITextFieldDelegate, SkillSelectViewControllerDelegate>

{
    NSString *_skill;
}

@property (weak, nonatomic) IBOutlet UITableView *MineSettingTable;
/** 注释 **/
@property (strong, nonatomic) UIImagePickerController * pickController;
/** 注释 **/
@property (strong, nonatomic) MineSettingFirstCell * MineFirstCell;
/** 注释 **/
@property (strong, nonatomic) MineSettingSeconodCell * MineSecondCell;
@property (nonatomic,strong) MineIntroSettingCell * Introfriend;
@property (nonatomic,strong) MineSettingSkillCell *skillCell;

@property (nonatomic,strong)  UIImage * headImage;
@property (nonatomic,strong)  NSData * headdata;
@property (nonatomic,copy) NSString * teach_descs;

@end

@implementation MineSettingVC


- (instancetype)initWithSkil:(NSString *)skill
{
    self = [super init];
    if (self) {
        _skill = skill;
    }
    return self;
}

- (void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    NSString * urlstr = [NSString stringWithFormat:@"%@",self.head_URLStr];
    
    if (urlstr ==NULL ||urlstr == nil) {
        [self.MineFirstCell.MineSettingUserHead setImage:[UIImage imageNamed:@"touxiang"]];
    }else{
        [self.MineFirstCell.MineSettingUserHead sd_setImageWithURL:self.head_URLStr placeholderImage:[UIImage imageNamed:@"touxiang"]];
    }
    
    if ([[XJToolClass getUserDic] isKindOfClass:[NSDictionary class]]) {
        
        if (self.teach_descs == nil || self.teach_descs.length ==0) {
            self.Introfriend .MineIntroDetailLab.text = [NSString stringWithFormat:@"技能:%@",[XJToolClass getUserDic][@"desc"]];
        }else{
            self.Introfriend .MineIntroDetailLab.text = [NSString stringWithFormat:@"技能:%@",self.teach_descs];
        }
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.navigationController setNavigationBarHidden:NO];
    [self addRightLabel:@"保存" Action:@selector(saveSettingInformation)];
    
    self.title = @"设置";
    self.MineSettingTable.backgroundColor = RGBA(230, 230, 230, 1);
    [self MineTableViewController];
    
}

- (void)saveSettingInformation{
    
    UIAlertController * aler = [UIAlertController alertControllerWithTitle:@"确定要修改吗？" message:nil preferredStyle:0];
    
    UIAlertAction * actionthree = [UIAlertAction actionWithTitle:@"确定" style:0 handler:^(UIAlertAction *action) {
        
        if (self.MineSecondCell.MineSettingInformationText.text != nil) {
          
        [XJHttpClass FixTeachNicknameProducttoken:[XJToolClass getToken] nickname:self.MineSecondCell.MineSettingInformationText.text desc:self.teach_descs andFinishblock:^(id response, NSString *errStr) {
            if (errStr) {
                [XJToolClass tipAnimationWith:errStr];
            }else{
                
                [XJToolClass tipAnimationWith:@"修改成功"];
                [XJToolClass removeNickname];
                [XJToolClass saveNickname:self.MineSecondCell.MineSettingInformationText.text];
            }
          }];
        }
        [self.navigationController popViewControllerAnimated:YES];
    }];
    UIAlertAction * actionfour = [UIAlertAction actionWithTitle:@"取消" style:1 handler:^(UIAlertAction *action) {
        [self.navigationController popViewControllerAnimated:YES];
    }];
    
    [aler addAction:actionthree];
    [aler addAction:actionfour];
    [self presentViewController:aler animated:YES completion:nil];
}

- (void)MineTableViewController{
    
    self.MineSettingTable.delegate = self;
    self.MineSettingTable.dataSource = self;
    self.MineSettingTable.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    [self.MineSettingTable registerNib:[UINib nibWithNibName:@"MineSettingFirstCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"MineSettingFirstCell"];
    
    [self.MineSettingTable registerNib:[UINib nibWithNibName:@"MineSettingSeconodCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"MineSettingSeconodCell"];
    [self.MineSettingTable registerNib:[UINib nibWithNibName:@"MineIntroSettingCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"MineIntroSettingCell"];
    [self.MineSettingTable registerNib:[UINib nibWithNibName:@"NicknameAndPhoneCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"NicknameAndPhoneCell"];
    [self.MineSettingTable registerNib:[UINib nibWithNibName:@"SettingExitBottom" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"SettingExitBottom"];
    
    [self.MineSettingTable registerNib:[UINib nibWithNibName:@"MineSettingSkillCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"MineSettingSkillCell"];

    self.pickController = [[UIImagePickerController alloc]init];
    self.pickController.allowsEditing = YES;
    self.pickController.delegate = self;
    
}

#pragma mark - TableViewDatasource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 8;
}

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        
        self.MineFirstCell = [tableView dequeueReusableCellWithIdentifier:@"MineSettingFirstCell" ];
        self.MineFirstCell.userInteractionEnabled = YES;
        
        self.MineFirstCell.MineSettingUserHead.layer.masksToBounds = YES;
        self.MineFirstCell.MineSettingUserHead.layer.cornerRadius = 30.5;
        NSString * urlstr = [NSString stringWithFormat:@"%@",self.head_URLStr];
        if (urlstr ==NULL ||urlstr == nil) {
            [self.MineFirstCell.MineSettingUserHead setImage:[UIImage imageNamed:@"touxiang"]];
        }else{
            [self.MineFirstCell.MineSettingUserHead sd_setImageWithURL:self.head_URLStr placeholderImage:[UIImage imageNamed:@"touxiang"]];
        }
        
        if ([[XJToolClass getUserDic] isKindOfClass:[NSDictionary class]]) {
            
            if (self.teach_descs == nil || self.teach_descs.length ==0) {
                self.Introfriend .MineIntroDetailLab.text = [NSString stringWithFormat:@"技能:%@",[XJToolClass getUserDic][@"desc"]];
            }else{
                self.Introfriend .MineIntroDetailLab.text = [NSString stringWithFormat:@"技能:%@",self.teach_descs];
            }
        }
        self.MineFirstCell.Tech_MineName.text = [XJToolClass getUserDic][@"truename"];
        return self.MineFirstCell;
        
    }else if (indexPath.row == 1){
        self.MineSecondCell = [tableView dequeueReusableCellWithIdentifier:@"NicknameAndPhoneCell"];
        self.MineSecondCell.MineSettingLeftName.text = @"昵称:";
        self.MineSecondCell.MineSettingInformationText.delegate = self;
         self.MineSecondCell.MineSettingInformationText.placeholder = [XJToolClass getNickname];
        return self.MineSecondCell;
        
    }else if (indexPath.row == 2){
        MineSettingSeconodCell * friend = [tableView dequeueReusableCellWithIdentifier:@"NicknameAndPhoneCell"];
        friend.MineSettingLeftName.text = @"手机:";
        friend.MineSettingInformationText.text = [XJToolClass getCurrentPhoneStr];
        friend.MineSettingInformationText.enabled = NO;
        return friend;
        
    }else if (indexPath.row == 3){
        
       self.skillCell = [tableView dequeueReusableCellWithIdentifier:@"MineSettingSkillCell"];
        if ([[XJToolClass getUserDic] isKindOfClass:[NSDictionary class]]) {
            
            if (_skill) {
                self.skillCell .MineSettingLeftName.text = @"技能";
                self.skillCell .MineSettingInformationText.text = _skill;
            }else{
                self.skillCell .MineSettingLeftName.text = @"技能";
            }
        }
        
        return self.skillCell ;
    
    }else if (indexPath.row == 4){
        MineSettingSeconodCell * friend=[tableView dequeueReusableCellWithIdentifier:@"MineSettingSeconodCell"];
        friend.MineSettingLeftName.text = @"意见反馈";
        friend.MineSettingInformationText.userInteractionEnabled = NO;
        return friend;
        
    }else if (indexPath.row == 5){
        MineSettingSeconodCell * friend=[tableView dequeueReusableCellWithIdentifier:@"MineSettingSeconodCell"];
        friend.MineSettingLeftName.text = @"帮助中心";
        friend.MineSettingInformationText.userInteractionEnabled = NO;
        return friend;
        
    }else if (indexPath.row == 6){
      
        MineSettingSeconodCell * friend=[tableView dequeueReusableCellWithIdentifier:@"MineSettingSeconodCell"];
        friend.MineSettingLeftName.text = @"关于我们";
        friend.MineSettingInformationText.userInteractionEnabled = NO;
        return friend;
        
    }else{
        
        SettingExitBottom * friend=[tableView dequeueReusableCellWithIdentifier:@"SettingExitBottom"];
        [friend.ExitLoginMeth addTarget:self action:@selector(SettingExitLoginMeth) forControlEvents:UIControlEventTouchUpInside];
        friend.ExitLoginMeth.layer.cornerRadius =20;
        friend.ExitLoginMeth.layer.masksToBounds = YES;
        
        return friend;
        
    }
}

#pragma mark TableViewDelegate
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        
        return 97+8;
        
    }else if (indexPath.row == 6){
        return 50;
    }else if (indexPath.row == 3){
        return 58;
    }else{
        return 50;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //当手指离开某行时，就让某行的选中状态消失
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    [self.view endEditing:YES];
    
    if (indexPath.row == 0) {
        
        [self selectHeadImage];
        
    }else if (indexPath.row == 1){
        
    }else if (indexPath.row == 2){
        
    }else if (indexPath.row == 3){
        
        SkillSelectViewController *controller = [[SkillSelectViewController alloc] init];
        controller.delegate = self;
        [self.navigationController pushViewController:controller animated:YES];
       
    }else if (indexPath.row == 4){
        
        AdviceFeedBackVC *feedBack = [[AdviceFeedBackVC alloc]init];
        [self.navigationController pushViewController:feedBack animated:YES];
        
    }else if (indexPath.row == 5){
        
        Customer_HelpCenter *minecollect = [[Customer_HelpCenter alloc]init];
        [self.navigationController pushViewController:minecollect animated:YES];
        
    }else{
        
        MineAboutVC * minecollect = [[MineAboutVC alloc]init];
        [self.navigationController pushViewController:minecollect animated:YES];
    }
}

- (void)SkillSelectViewController:(SkillSelectViewController *)controller skills:(NSString *)skills
{
    self.skillCell .MineSettingInformationText.text = skills;
}

-(void)selectHeadImage
{
    UIAlertController * aler = [UIAlertController alertControllerWithTitle:@"选取照片" message:nil preferredStyle:0];
    UIAlertAction * actionone = [UIAlertAction actionWithTitle:@"照片库" style:0 handler:^(UIAlertAction *action) {
        
        self.pickController.sourceType = UIImagePickerControllerCameraCaptureModePhoto;
        [self presentViewController:self.pickController animated:YES completion:^{
            
        }];
    }];
    
    UIAlertAction * actiontwo = [UIAlertAction actionWithTitle:@"拍照" style:0 handler:^(UIAlertAction *action) {
        
        if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            
            UIAlertController * a = [UIAlertController alertControllerWithTitle:@"提示" message:@"该设备不存在摄像功能或摄像已损坏！" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction * act = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
            }];
            [a addAction:act];
            [self presentViewController:a animated:YES completion:nil];
            
        }else
        {
            self.pickController.sourceType = UIImagePickerControllerSourceTypeCamera;
            [self presentViewController:self.pickController animated:YES completion:nil];
        }
        
    }];
    UIAlertAction * actionthree = [UIAlertAction actionWithTitle:@"胶卷" style:0 handler:^(UIAlertAction *action) {
        self.pickController.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
        [self presentViewController:self.pickController animated:YES completion:nil];
    }];
    UIAlertAction * actionfour = [UIAlertAction actionWithTitle:@"取消" style:1 handler:^(UIAlertAction *action) {
    }];
    
    [aler addAction:actionone];
    [aler addAction:actiontwo];
    [aler addAction:actionthree];
    [aler addAction:actionfour];
    
    [self presentViewController:aler animated:YES completion:nil];
}

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    
    [self dismissViewControllerAnimated:YES completion:^{
        [self.MineFirstCell.MineSettingUserHead setImage:info[UIImagePickerControllerEditedImage]];
    }];
    
    self.headImage = info[UIImagePickerControllerEditedImage];
    
    [LoadingView showCircleView:self.view];
    [XJHttpClass ReceiveQiniuTokenFinishblock:^(id response, NSString *errStr) {
        if (errStr) {
            [XJToolClass tipAnimationWith:errStr];
        }else{
            
            NSDictionary * datadict = response[@"data"];
            NSString * qiniu_token = datadict[@"upToken"];
            
            self.headdata = UIImagePNGRepresentation(self.headImage);
            QNUploadManager *upManager = [[QNUploadManager alloc] init];
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            [formatter setDateFormat:@"YYYYMMddHHmmss"];
            NSDate *datenow = [NSDate date];
            
            NSString *currentTimeString = [NSString stringWithFormat:@"%@.jpg",[formatter stringFromDate:datenow]];
            QNUploadOption *opt = [[QNUploadOption alloc] initWithMime:@"text/plain" progressHandler:nil params:@{ @"x:foo":@"fooval" } checkCrc:YES cancellationSignal:nil];
            
            __block QNResponseInfo *testInfo = nil;
            __block NSDictionary *testResp = nil;
            
            [upManager putData:self.headdata key:currentTimeString token:qiniu_token
                      complete: ^(QNResponseInfo *info, NSString *key, NSDictionary *resp) {
                          
                          [LoadingView hide];
                          testInfo = info;
                          testResp = resp;
                          
                          NSString * Identity_Fontet = [NSString stringWithFormat:@"%@/%@",kQiniuBaseUrl,resp[@"key"]];
                          [XJHttpClass FixTeachHeadImageToken:qiniu_token headurl:Identity_Fontet andFinishblock:^(id response, NSString *errStr) {
                              if (errStr) {
                                  [XJToolClass tipAnimationWith:errStr];
                              }else{
                                  [XJToolClass removeHeadImg];
                                  [XJToolClass saveHeadImg:Identity_Fontet];
                              }
                          }];
                          
                      } option:opt];
            
            if (testInfo.isOK) {
                //给定时
                [NSTimer scheduledTimerWithTimeInterval:4 target:self selector:@selector(defaileduploadheadimage) userInfo:nil repeats:NO];
            }
        }
    }];
}

-(void)defaileduploadheadimage{
    
    [LoadingView hide];
    [XJToolClass tipAnimationWith:@"网络连接不稳定,上传失败！"];
}

- (void)SettingExitLoginMeth{
    
    [XJToolClass removeUserdic];
    [XJToolClass removeUserId];
    [XJToolClass removeAccount];
    [XJToolClass removeToken];
    [XJToolClass removePasswd];
    [XJToolClass removeHeadImg];
    [XJToolClass removePhonenumber];
    [XJToolClass removeNickname];
    [XJToolClass removeAvater];
    
    if ([self.delegate respondsToSelector:@selector(logoutWithController:)]) {
        [self.delegate logoutWithController:self];
    }
    
    [self.navigationController popViewControllerAnimated:YES];
    
    
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    
    [self.MineSecondCell.MineSettingInformationText resignFirstResponder];
    
    return NO;
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    [self.MineSecondCell.MineSettingInformationText resignFirstResponder];
    
}

@end
